package com.ls.utils;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CGLibTest {
	public static void main(String[] args) {
		TargetDymaticProxy proxy = new TargetDymaticProxy(new Target());
		Target t = proxy.getObject(Target.class);
		System.out.println(t.getClass());
		t.hello();
	}
}

class TargetDymaticProxy implements MethodInterceptor {
	private Object target;

	public TargetDymaticProxy(Object target) {
		this.target = target;
	}

	@SuppressWarnings("unchecked")
	public <T> T getObject(Class<T> t) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(getTarget().getClass());
		enhancer.setCallback(this);
		return (T) enhancer.create();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		before();
		proxy.invokeSuper(obj, args);
		after();
		return null;
	}

	private void after() {
		System.out.println("after");

	}

	private void before() {
		System.out.println("before");
	}

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

}

class Target {
	public void hello() {
		System.out.println("target");
	}
}
